package com.icesoft.core.web.suppose.upload.base;

import cn.hutool.core.io.IoUtil;
import com.icesoft.core.common.exception.CheckNoLogException;
import com.icesoft.core.common.util.MD5Util;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public abstract class BaseFileUploadTemplate {
    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    protected abstract BaseUploadPathConfig getPathConfig();


    public String writeToFile(ChunkFileDTO chunkFileDTO, InputStream is) {
        return writeToFile(chunkFileDTO, IoUtil.readBytes(is));
    }

    public String writeToFile(ChunkFileDTO chunkFileDTO, byte[] fileData) {
        File outFile = new File(getPathConfig().getOutFilePath(chunkFileDTO.md5, chunkFileDTO.fileName));
        ChunkFileUtil.write(chunkFileDTO, outFile, fileData);
        if (chunkFileDTO.isEndChunk() && !checkOutFile(chunkFileDTO, outFile)) {
            checkOutFileFail(outFile);
            throw new CheckNoLogException("文件校验失败，请重试");
        }
        getPathConfig().uploadFinish(outFile);
        return outFile.getAbsolutePath();
    }

    public boolean checkOutFile(ChunkFileDTO chunkFileDTO, File outFile) {
        // md5校验
        String serverMd5 = MD5Util.md5(outFile);
        if (!chunkFileDTO.md5.equals(serverMd5)) {
            log.error("文件校验失败：{},serverMd5:{}", outFile.getAbsolutePath(), serverMd5);
            return false;
        }
        return true;
    }

    private void checkOutFileFail(File outFile) {
        try {
            boolean suc = outFile.renameTo(new File(outFile.getAbsolutePath() + ".error"));
            if (suc) {
                FileUtils.forceDelete(outFile);
            }
        } catch (IOException e) {
            log.error("forceDelete error", e);
        }
    }

}
